<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ImageController extends Controller
{

    public $IOURL; // 文件上传路径
    public $ROOTURL; // 项目根目录
    public $ShearURL; // 文件上传路径
    public $ShearPhoto; //上传裁剪设置
    public $ini_set; //上传设置
    public $UpFile = array(); //上传文件设置
    public $erro = false;
    public $int_type;

    //上传多张图片

    public function upPicMore()
    {
        // Make sure file is not cached (as it happens for example on iOS devices)
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");

        // Support CORS
        // header("Access-Control-Allow-Origin: *");
        // other CORS headers if any...
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }
        if (!empty($_REQUEST['debug'])) {
            $random = rand(0, intval($_REQUEST['debug']));
            if ($random === 0) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }

        // header("HTTP/1.0 500 Internal Server Error");
        // exit;
        // 5 minutes execution time
        @set_time_limit(5 * 60);

        // Uncomment this one to fake upload time
        usleep(5000);

        // Settings
        // $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
        if (isset($_REQUEST["foldername"])) {
            $targetDir .= 'Public/Uploads/' . $_REQUEST["foldername"] . '_tmp';
            $uploadDir .= 'Public/Uploads/' . $_REQUEST["foldername"];
        } else {
            $targetDir .= 'Public/Uploads/Images_tmp';
            $uploadDir .= 'Public/Uploads/Images';
        }

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds
        // Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }

        // Create target dir
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir);
        }

        // Get a file name
        if (isset($_REQUEST["name"])) {
            $types = explode('.', $_REQUEST["name"]);
            $fileName = md5(time() . rand(5, 25)) . '.' . $types[1];
        } elseif (!empty($_FILES)) {
            $types = explode('.', $_FILES["file"]["name"]);
            $fileName = md5(time() . rand(5, 25)) . '.' . $types[1];
        } else {
            $fileName = md5(time() . rand(5, 25)) . uniqid("file_");
        }

        $md5File = @file('md5list.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $md5File = $md5File ? $md5File : array();

        if (isset($_REQUEST["md5"]) && array_search($_REQUEST["md5"], $md5File) !== FALSE) {
            die('{"jsonrpc" : "2.0", "result" : null, "id" : "id", "exist": 1,"picurl": ,}');
        }
        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;


        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;


        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }


        // Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");

        $index = 0;
        $done = true;
        for ($index = 0; $index < $chunks; $index++) {
            if (!file_exists("{$filePath}_{$index}.part")) {
                $done = false;
                break;
            }
        }
        if ($done) {
            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if (flock($out, LOCK_EX)) {
                for ($index = 0; $index < $chunks; $index++) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);
        }

        // Return Success JSON-RPC response
        $imgdata = array('jsonrpc' => 2.0, 'result' => null, 'id' => $chunks, 'picurl' => '/' . $uploadPath,);
        $this->ajaxReturn($imgdata);
        //die('{"jsonrpc" : "2.0", "result" : null, "id" : "id","picurl":$uploadPath}');
        // Define a destination
    }

    //图片上传裁剪示例
//    public function index() {
//        $this->display();
//    }
    //图片上传
    public function upPicOne()
    {
        $file = $_POST['imgfile'];
        if ($file) { //图片保存文件夹
            $file = $file . "/";
        }
        $config = array(
            'maxSize' => 3145728,
            'rootPath' => './Public/Uploads/' . $file,
            'exts' => array('jpg', 'gif', 'png', 'jpeg'),
            'subName' => '',
        );
        $upload = new \Think\Upload($config); // 实例化上传类
        // 上传文件 

        $info = $upload->uploadOne($_FILES['file']);
        $url = "/Public/Uploads/" . $file . $info['savepath'] . $info['savename'];
        if (!$info) {
            $this->ajaxReturn("false", "EVAL");
        } else {
            $this->ajaxReturn($url, "EVAL");
        }
    }

    //删除图片
    public function delimg()
    {
        $imgurl = $_POST["imgurl"]; //之前长传的图片
        unlink("." . $imgurl); //删除之前的图片
        $this->ajaxReturn(true);
    }

    //图片裁剪保存
    public function imgcrop()
    {
        if ($_POST) {
            //获取原图路径
            $src = $_POST['src'];
            //取得原图像的信息
            $source_path = substr($src, 1); //截取“/Public”后面的字母
            //取得原图像的信息
            $source_info = getimagesize($source_path);
            $source_w = $source_info[0];
            $source_h = $source_info[1];
            $source_mime = $source_info['mime'];

            //取得页面截取参数
            $postx = $_POST['x'];
            $posty = $_POST['y'];
            $postw = $_POST['w'];
            $posth = $_POST['h'];

            //确定实际图像的x、y、w、h
            $true_x = $postx;
            $true_y = $posty;
            $true_w = $postw;
            $true_h = $posth;
            //目标存储规格
            $targ_w = $_POST['targw'];
            $targ_h = $_POST['targh'];
            $jpeg_quality = 90;
            //根据图片类型创建
            switch ($source_mime) {
                case 'image/gif':
                    $source_image = imagecreatefromgif($source_path);
                    break;

                case 'image/jpeg':
                    $source_image = imagecreatefromjpeg($source_path);
                    break;

                case 'image/png':
                    $source_image = imagecreatefrompng($source_path);
                    break;

                default:
                    return false;
                    break;
            }
            $dst_r = ImageCreateTrueColor($targ_w, $targ_h);
            imagecopyresampled($dst_r, $source_image, 0, 0, $true_x, $true_y, $targ_w, $targ_h, $true_w, $true_h);

            //获取文件的路径
            $fileurls = explode(".", $src);
            $rand = rand(10, 99);
            //根据图片类型存储图片
            switch ($source_mime) {
                case 'image/gif':
                    imagegif($dst_r, $source_path);
                    rename("." . $src, "." . $fileurls[0] . $rand . ".gif");
                    $newSrc = $fileurls[0] . $rand . ".gif";
                    break;

                case 'image/jpeg':
                    imagejpeg($dst_r, $source_path, $jpeg_quality);
                    rename("." . $src, "." . $fileurls[0] . $rand . ".jpg");
                    $newSrc = $fileurls[0] . $rand . ".jpg";
                    break;

                case 'image/png':
                    imagepng($dst_r, $source_path);
                    rename("." . $src, "." . $fileurls[0] . $rand . ".png");
                    $newSrc = $fileurls[0] . $rand . ".png";
                    break;

                default:
                    return false;
                    break;
            }
            imagedestroy($dst_r);
            $this->ajaxReturn($newSrc);
        }
    }

    /**
     * deleteImgUrl
     * 删除图片
     * @return [type] [description]
     */
    public function deleteImgUrl()
    {
        $imgPath = $_POST['url'];
        unlink("." . $imgPath);
        $return['success'] = true;

        //$this->ajaxReturn($return);
        return ["success" => true];
    }

    /**
     * upload
     * 上传图片
     * @return [type] [description]
     */
    public function upload()
    {
        $this->shearphoteConfig();
        $this->shearphoteUpConfig();
        $UpFile = $this->UpFile;

        if (!move_uploaded_file($_FILES['UpFile']['tmp_name'], $UpFile['file_url'])) {
            $this->HandleError('后端获取不到文件写入权限。原因：move_uploaded_file()函数-无法写入文件');
        }
        $UpFile['file_url'] = str_replace(array('.' . DIRECTORY_SEPARATOR, "\\"), array(DIRECTORY_SEPARATOR, "/"), $UpFile['file_url']);
        /*
          来到这里时，已经代表上传成功，你可以在这里尽情写的你逻辑
          $UpFile['file_url']就是那张临时待截图片的路径！
         */
        echo('{"success":"' . $UpFile['file_url'] . '"}');
    }

    /**
     * shearphoto
     * 图片裁剪
     * @return [type] [description]
     */
    public function shearphoto()
    {
        $this->shearphoteConfig();

        if (isset($_POST["JSdate"])) {//普通截取时
            $ShearPhoto["JSdate"] = json_decode(trim(stripslashes($_POST["JSdate"])), true);
            $ShearPhoto["JSdate"]['url'] = "." . $ShearPhoto["JSdate"]['url'];

            $result = $this->run($ShearPhoto["JSdate"], $this->ShearPhoto["config"]);
            //传入参数运行
            if ($result === false) {//切图失败时
                echo '{"erro":"' . $this->erro . '"}';
                //把错误发给JS /请匆随意更改"erro"的编写方式，否则JS出错
                exit;
            } else {
                $dirname = pathinfo($ShearPhoto["JSdate"]["url"]);
                $ShearPhotodirname = $dirname["dirname"] . DIRECTORY_SEPARATOR . "shearphoto.lock";
                //认证删除的密钥
                file_exists($ShearPhotodirname) && @unlink($ShearPhoto["JSdate"]["url"]);
                //密钥存在，当然就删掉原图
            }
        } /* ........................HTML5截取时.......................... */ elseif (isset($_POST["ShearPhotoIW"]) && isset($_POST["ShearPhotoIH"]) && isset($_POST["ShearPhotoFW"]) && isset($_POST["ShearPhotoFH"]) && isset($_POST["ShearPhotoP"]) && is_numeric($JSconfig["P"] = trim($_POST["ShearPhotoP"])) && is_numeric($JSconfig["IW"] = trim($_POST["ShearPhotoIW"])) && is_numeric($JSconfig["IH"] = trim($_POST["ShearPhotoIH"])) && is_numeric($JSconfig["FW"] = trim($_POST["ShearPhotoFW"])) && is_numeric($JSconfig["FH"] = trim($_POST["ShearPhotoFH"]))) {
            //类实例开始
            $result = $this->html5_run($this->ShearPhoto["config"], $JSconfig);
            //加载HTML5已切好的图片独有方法
            if ($result === false) {//切图失败时
                echo '{"erro":"' . $this->erro . '"}';
                //把错误发给JS /请匆随意更改"erro"的编写方式，否则JS出错
                exit;
            }
        }
        /* ........................HTML5截取时结束.......................... */

        /* ........错误的操作................ */ else {
            die('{"erro":"错误的操作！或缺少参数或错误参数"}');
        }
        /* ........错误的操作................ */

        //用var_dump($result)展开，你便一目了然！
        // var_dump($result);die;
        $result[0]['ImgUrl'] = str_replace(array('./', "\\"), array(DIRECTORY_SEPARATOR, "/"), $result[0]['ImgUrl']);
        $str_result = json_encode($result);
        echo str_replace("\/", "/", $str_result);
    }

    /**
     * shearphoteConfig
     * 裁剪一些配置
     * @return [type] [description]
     */
    public function shearphoteConfig()
    {
        $this->IOURL = DIRECTORY_SEPARATOR . 'Public' . DIRECTORY_SEPARATOR . "Uploads";
        //锁定相对目录
        $this->ROOTURL = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR;
        $this->ShearURL = "." . $this->IOURL . DIRECTORY_SEPARATOR;
        $this->ShearPhoto["config"] = array("proportional" => false, //比例截图，如果你是动态比例，请设为false，false时就不会验证JS端的比例了。如果为数字时，JS端也要相应设置哦，不然系统会给你抱出错误,不设比例填0，如填比例 ：3/4  代表宽和高的比例是3/4(3除以4的意思懂吗，菜菜，你可直接填0.75，没错)
            "quality" => 85, // 截图质量，0为一般质量（质量大概75左右），  0-100可选 ！ 整数型，质量越高，越清淅，缺点是文件体积越大，不是太严格追求图片高清，设0就可以,提示：PNG图片不带此效果
            "force_jpg" => true, // 是否强制截好的图片是JPG格式  可选 true false
            "width" => array(//自定义设置生成截图的张数，大小，在这设，看好下面！
                //array(0,true,"name0"),//此时的0   代表以用户取当时截取框的所截的大小为宽
                //array(-1,true,"name1"),//此时的-1   代表以原图为基准，获得截图

                array(150, false, "primary"), //@参数1要生成的宽 （高度不用设，系统会按比例做事），    @参数2：是否为该图加水印，water参数要有水印地址才有效true或false  @参数3：图片后面添加字符串 （用以区分其他截图名称),填写字符串，不要含中文，不然能又鸡巴痛了 ，不定义的话默认为“0”
                //array(100, false, "thumbnail"), //@参数1要生成的宽 （高度不用设，系统会按比例做事），   @参数2：是否为该图加水印，water参数要有水印地址才有效true或false  @参数3：图片后面添加字符串 （用以区分其他截图名称),填写字符串，不要含中文，不然能又鸡巴痛了，不定义的话默认为"0"
            ), "water" => "../images/waterimg2.png", //只接受PNG水印，当然你对PHP熟练，你可以对主程序进行修改支持其他类型水印,不设就"water"=>false
            "water_scope" => 100, //图片少于多少不添加水印！没填水印地址，这里不起任何作用
            "temp" => $this->ShearURL . "temp", //等待截图的大图文件。就是上传图片的临时目录，截图后，图片会被删除,非HTML5切图就会用到它
            "tempSaveTime" => 600, //临时图片（也就是temp内的图片）保存时间，需要永久保存请设为0。单位秒
            "saveURL" => $this->ShearURL, //截好后的图片。储存的目录位置，后面不要加斜杠，系统会自动给补上！不要使用中文
            "filename" => uniqid("crop") . "_" . date('Ymdhis') . mt_rand(1000, 9999) . "_"//截好后的图片的文件名字定义！要生成多个文件时 系统会自动在后面补上  "width"=>array()参数定义的名称,请查看上面的"width"=>array()
        );
    }

    public function shearphoteUpConfig()
    {
        /* .......................注意.............HTML5上传截图，非HTML浏览器上传，拍照上传都会用到该文件哦，加入逻辑代码后。所有功能都要确保正确！............................注意......文件最后修改时间2015年9月29日..作者：明哥先生...................... */
        $this->ini_set = array('max_size' => 2 * 1024 * 1024, //文件大小限制设置  M单位
            'out_time' => 60, //上传超时设置
            'list' => $this->ShearPhoto["config"]["temp"] . DIRECTORY_SEPARATOR, //上传路径
            'whitelist' => array(".jpeg", ".gif", ".png", ".jpg")//上传的文件后缀
        );
        /* 设置部份结束 */
        ini_set('max_execution_time', $this->ini_set['out_time']);
        //var_dump($_FILES);die;
        if (!isset($_FILES['UpFile'])) {
            $this->HandleError();
        }
        if (isset($_FILES['UpFile']['error']) && $_FILES['UpFile']['error'] != 0) {
            $uploadErrors = array(0 => '文件上传成功', 1 => '上传的文件超过了 php.ini 文件中的 upload_max_filesize directive 里的设置', 2 => '上传的文件超过了 HTML form 文件中的 MAX_FILE_SIZE directive 里的设置', 3 => '上传的文件仅为部分文件', 4 => '没有文件上传', 6 => '缺少临时文件夹');
            $this->HandleError($uploadErrors[$_FILES['UpFile']['error']]);
        }
        if (!isset($_FILES['UpFile']['tmp_name']) || !@is_uploaded_file($_FILES['UpFile']['tmp_name'])) {
            $this->HandleError('无法找到上传的文件，上传失败');
        }
        if (!isset($_FILES['UpFile']['name'])) {
            $this->HandleError('上传空名字文件名');
        }
        $POST_MAX_SIZE = ini_get('post_max_size');
        $unit = strtoupper(substr($POST_MAX_SIZE, -1));
        $multiplier = $unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1));
        if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier * (int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
            $this->HandleError('超过POST_MAX_SIZE的设置值，请查看PHP.ini的设置');
        }
        $file_size = @filesize($_FILES['UpFile']['tmp_name']);
        if (!$file_size || $file_size > $this->ini_set['max_size']) {
            $this->HandleError('零字节文件 或 上传的文件已经超过所设置最大值');
        }

        $this->int_type = getimagesize($_FILES['UpFile']['tmp_name']);
        $str_type = image_type_to_extension($this->int_type[2]);
        if (!in_array(strtolower($str_type), $this->ini_set['whitelist'])) {
            $this->HandleError('不允许上传此类型文件');
        }
        $str_type == ".jpeg" && ($str_type = ".jpg");
        $this->UpFile['filename'] = uniqid("temp_") . "_" . mt_rand(100, 999) . $str_type;

        $this->UpFile['file_url'] = $this->ini_set['list'] . $this->UpFile['filename'];

        file_exists($this->ini_set['list']) or @ mkdir($this->ini_set['list'], 511, true);
    }

    /**
     * HandleError
     * 错误
     * @return [type] [description]
     */
    public function HandleError($erro = '系统错误')
    {
        die('{"erro":"' . $erro . '"}');
    }

    protected function rotate($src, $R)
    {
        $arr = array(90, 180, 270);
        if (in_array($R, $arr)) {
            $rotatesrc = imagerotate($src, $R, 0);
            imagedestroy($src);
        } else {
            return $src;
        }
        return $rotatesrc;
    }

    public function html5_run(&$PHPconfig, &$JSconfig)
    {
        $this->shearphoteUpConfig();
        $ShearPhoto["config"] = $PHPconfig;
        if (is_bool($PHPconfig["proportional"])) {
            $PHPconfig["proportional"] = $JSconfig["P"];
        } elseif ($PHPconfig["proportional"] != $JSconfig["P"]) {
            $this->erro = "JS设置的比例和PHP设置不一致！";
            return false;
        }

        $tempurl = $PHPconfig["temp"] . DIRECTORY_SEPARATOR . "shearphoto.lock";
        !file_exists($tempurl) && file_put_contents($tempurl, "ShearPhoto Please don't delete");
        $this->delTempImg($PHPconfig["temp"], $PHPconfig["tempSaveTime"]);
        $imagecreatefrom = $this->imagecreatefrom($_FILES['UpFile']['tmp_name'], $this->int_type[2]);
        if (!$imagecreatefrom)
            return false;
        list($src, $GdFun) = $imagecreatefrom;
        return $this->compression($src, $PHPconfig, $JSconfig, $this->int_type[2], $GdFun);
    }

    protected function delTempImg($temp, $deltime)
    {
        if ($deltime == 0)
            return;
        $dir = opendir($temp);
        $time = time();
        while (($file = readdir($dir)) !== false) {
            if ($file != "." and $file != ".." and $file != "shearphoto.lock") {
                $fileUrl = $temp . DIRECTORY_SEPARATOR . $file;
                $pastTime = $time - filemtime($fileUrl);
                if ($pastTime < 0 || $pastTime > $deltime)
                    @unlink($fileUrl);
            }
        }
        closedir($dir);
    }

    public function run(&$JSconfig, &$PHPconfig)
    {
        $tempurl = $PHPconfig["temp"] . DIRECTORY_SEPARATOR . "shearphoto.lock";
        !file_exists($tempurl) && file_put_contents($tempurl, "ShearPhoto Please don't delete");
        $this->delTempImg($PHPconfig["temp"], $PHPconfig["tempSaveTime"]);
        if (!isset($JSconfig["url"]) || !isset($JSconfig["R"]) || !isset($JSconfig["X"]) || !isset($JSconfig["Y"]) || !isset($JSconfig["IW"]) || !isset($JSconfig["IH"]) || !isset($JSconfig["P"]) || !isset($JSconfig["FW"]) || !isset($JSconfig["FH"])) {
            $this->erro = "服务端接收到的数据缺少参数";
            return false;
        }
        if (!file_exists($JSconfig["url"])) {
            $this->erro = "此图片路径有误";
            return false;
        }
        foreach ($JSconfig as $k => $v) {
            if ($k !== "url") {//验证是否为数字除了url参数之外
                if (!is_numeric($v)) {
                    $this->erro = "传递的参数有误";
                    return false;
                }
            }
        }
        if (is_bool($PHPconfig["proportional"])) {
            $PHPconfig["proportional"] = $JSconfig["P"];
        } elseif ($PHPconfig["proportional"] != $JSconfig["P"]) {
            $this->erro = "JS设置的比例和PHP设置不一致！";
            return false;
        }
        list($w, $h, $type) = getimagesize($JSconfig["url"]);
        $strtype = image_type_to_extension($type);
        $type_array = array(".jpeg", ".gif", ".png", ".jpg");
        if (!in_array(strtolower($strtype), $type_array)) {
            $this->erro = "无法读取图片";
            return false;
        }

        if ($JSconfig["R"] == 90 || $JSconfig["R"] == 270) {
            list($w, $h) = array($h, $w);
        }
        return $this->createshear($PHPconfig, $w, $h, $type, $JSconfig);
    }

    protected function imagecreatefrom($url, $type)
    {
        switch ($type) {
            case 1 :
                $src = @imagecreatefromgif($url);
                $GdFun = array("imagegif", ".gif");
                break;

            case 2 :
                $src = @imagecreatefromjpeg($url);
                $GdFun = array("imagejpeg", ".jpg");
                break;

            case 3 :
                $src = @imagecreatefrompng($url);
                $GdFun = array("imagepng", ".png");
                break;

            default :
                $this->erro = "不支持的类型";
                return false;
                break;
        }
        return array($src, $GdFun);
    }

    protected function createshear(&$PHPconfig, $w, $h, $type, &$JSconfig)
    {
        $imagecreatefrom = $this->imagecreatefrom($JSconfig["url"], $type);
        if (!$imagecreatefrom)
            return false;
        list($src, $GdFun) = $imagecreatefrom;
        $src = $this->rotate($src, $JSconfig["R"]);
        $dest = imagecreatetruecolor($JSconfig["IW"], $JSconfig["IH"]);
        $white = imagecolorallocate($dest, 255, 255, 255);
        imagefill($dest, 0, 0, $white);
        imagecopy($dest, $src, 0, 0, $JSconfig["X"], $JSconfig["Y"], $w, $h);
        imagedestroy($src);
        return $this->compression($dest, $PHPconfig, $JSconfig, $type, $GdFun);
    }

    protected function CreateArray(&$PHPconfig, &$JSconfig)
    {
        $arr = array();
        if ($PHPconfig["proportional"] > 0) {
            $proportion = $PHPconfig["proportional"];
        } else {
            $proportion = $JSconfig["IW"] / $JSconfig["IH"];
        }
        $water_or = isset($PHPconfig["water"]) && $PHPconfig["water"] && file_exists($PHPconfig["water"]) && is_numeric($PHPconfig["water_scope"]);
        if (!file_exists($PHPconfig["saveURL"])) {
            if (!mkdir($PHPconfig["saveURL"], 0777, true)) {
                $this->erro = "目录权限有问题";
                return false;
            }
        }

        if ($_POST["saveUrl"]) {
            $file_url = $PHPconfig["saveURL"] . $_POST["saveUrl"] . DIRECTORY_SEPARATOR . $PHPconfig["filename"];
        } else {
            $file_url = $PHPconfig["saveURL"] . $PHPconfig["filename"];
        }
        foreach ($PHPconfig["width"] as $k => $v) {
            ($v[0] == 0) ? ($v[0] = $JSconfig["FW"]) : ($v[0] == -1) and ($v[0] = $JSconfig["IW"]);
            $v[0] = $_POST["shearphoto"] ? $_POST["shearphoto"] : $v[0];
            $height = $v[0] / $proportion;
            $suffix = isset($v[2]) ? $v[2] : "0";
            $arr[$k] = array($v[0], $height, $file_url . $suffix, ($v[1] === true and $water_or === true and $v[0] > $PHPconfig["water_scope"] and $height > $PHPconfig["water_scope"]));
        }
        return array($water_or, $arr);
    }

    protected function compression($DigShear, &$PHPconfig, &$JSconfig, $type, $GdFun)
    {
        vendor('zip_img');
        $arrimg = $this->CreateArray($PHPconfig, $JSconfig);
        if (count($arrimg[1]) < 1) {
            $this->erro = "系统没有检测到处理截图的命令！";
            return false;
        }
        $arrimg[0] and $arrimg[0] = $PHPconfig["water"];

        $zip_photo = new \zip_img(array("dest" => $DigShear, "GdFun" => $GdFun, "quality" => isset($PHPconfig["quality"]) ? $PHPconfig["quality"] : false, "force_jpg" => isset($PHPconfig["force_jpg"]) && $PHPconfig["force_jpg"], "water" => $arrimg[0], "water_scope" => $PHPconfig["water_scope"], "w" => $JSconfig["IW"], "h" => $JSconfig["IH"], "type" => $type, "zip_array" => $arrimg[1]));
        return $zip_photo->run($this);
    }

    public function showCropper()
    {
        return view('admin.showCropper');
    }

}
